package fichier;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

import java.io.File;
import java.sql.*;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * @author Yann LARRIAU
 *
 */

public class AjouterModele extends JFrame implements ActionListener, KeyListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8322414900706093065L;
	private JPanel pane;
	private JLabel designation;
	private JLabel client;
	private JLabel box;
	private JLabel annee;
	private JLabel numero;
	private JLabel numeroPlan;
	private JLabel commentaire;
	private JLabel nbMoules;
	private JLabel nbBoites;
	private JLabel image;
	private JComboBox clientBox ;
	private JComboBox boxBox ;
	private JTextField anneeTxt;
	private JTextField designationTxt;
	private JTextField numeroTxt;
	private JTextField numeroPlanTxt;
	private JTextField commentaireTxt;
	private JTextField nbMoulesTxt;
	private JTextField nbBoitesTxt ;
	private JTextField imageTxt;
	private JButton okBut ;
	private JButton cancBut ;
	private JButton	parcourirBut;
	private JMenuBar menuBar;
	private JMenu fichier;
	private JMenu mModele;
	private JMenu mClient;
	private JMenuItem deconnexion;
	private JMenuItem miRechercherM;
	private JMenuItem miAjouterM;
	private JMenuItem miAjouterC;
	public String[] clientboxtab;
	public String[] boxboxtab;
	private File imageFile;
	public static final String pathImage = "/Users/yannlarriau/Documents/workspace/Model Manager/Images/";
	public AjouterModele()
	{
		super("Model Manager");
		this.setBounds(100,100,550,360 );
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.imageFile = new File(pathImage + "imagenonexistante.jpg");

		/*****
		 *****  S�lection des noms de clients et de Boxes pour les combobox
		 *****
		 *****/



		SelectData.REQUETE  = "SELECT id_client, nom_client FROM client ORDER BY id_client";
		ResultSet lignes = SelectData.startSelect();

		int nbligne=0;

		try{

			while(lignes.next()){
				nbligne++;
			}

		}
		catch(SQLException e){
			System.out.println("error"); 
		}

		this.clientboxtab = new  String[nbligne+1];

		SelectData.REQUETE  = "SELECT id_client, nom_client FROM client ORDER BY id_client";
		ResultSet resultat = SelectData.startSelect();
		int i=1;
		this.clientboxtab[0] = "";

		try{
			while(resultat.next()){
				this.clientboxtab [i] = resultat.getString("nom_client");
				i++;
			}

		}
		catch(SQLException e){
			System.out.println("error"); 
		}

		SelectData.REQUETE  = "SELECT id_box, nom_box FROM box ORDER BY id_box";
		ResultSet lignesfr = SelectData.startSelect();
		nbligne=0;

		try{
			while(lignesfr.next()){
				nbligne++;
			}

		}
		catch(SQLException e){
			System.out.println("error"); 
		}

		this.boxboxtab = new  String[nbligne+1];

		SelectData.REQUETE  = "SELECT id_box, nom_box FROM box ORDER BY id_box";
		resultat = SelectData.startSelect();
		i=1;
		this.boxboxtab[0] = "";

		try{
			while(resultat.next()){
				this.boxboxtab [i] = resultat.getString("nom_box");
				i++;
			}

		}
		catch(SQLException e){
			System.out.println(""); 
		}


		this.menuBar = new JMenuBar();
		this.fichier = new JMenu("Fichier");
		this.mModele = new JMenu("Modèle");
		this.mClient = new JMenu("Client");
		this.deconnexion = new JMenuItem("Déconnexion");
		this.miRechercherM = new JMenuItem("Rechercher");
		this.miAjouterM = new JMenuItem("Ajouter");
		//this.setMiModifierM(new JMenuItem("Modifier"));
		this.miAjouterC = new JMenuItem("Ajouter");

		this.menuBar.add(this.fichier);
		this.menuBar.add(this.mModele);
		this.menuBar.add(this.mClient);
		this.fichier.add(this.deconnexion);
		this.mModele.add(this.miRechercherM);
		this.mModele.add(this.miAjouterM);
		this.mClient.add(this.miAjouterC);
		this.setJMenuBar(this.menuBar);

		this.pane = new JPanel();
		this.designation = new JLabel("Désignation");
		this.client = new JLabel("Client");
		this.box = new JLabel("N° Box");
		this.annee = new JLabel("Année");
		this.numero = new JLabel("Numéro");
		this.numeroPlan = new JLabel("N° Plan");
		this.commentaire = new JLabel("Commentaire");
		this.nbMoules = new JLabel("Nombre de Modèles");
		this.nbBoites = new JLabel("Nombre de Boites");
		this.image = new JLabel("Image");
		this.clientBox = new JComboBox(clientboxtab);
		this.boxBox = new JComboBox(boxboxtab);
		this.anneeTxt = new JTextField("");
		this.designationTxt = new JTextField("");
		this.numeroTxt = new JTextField("");
		this.numeroPlanTxt = new JTextField("");
		this.commentaireTxt = new JTextField("");
		this.nbMoulesTxt = new JTextField("");
		this.nbBoitesTxt = new JTextField("");
		this.imageTxt = new JTextField("");
		this.okBut = new JButton("Ajouter");
		this.cancBut = new JButton("Annuler");
		this.parcourirBut = new JButton("parcourir");
		this.pane.setBorder(BorderFactory.createTitledBorder("Ajout de modèle"));

		this.parcourirBut.setEnabled(false);
		this.imageTxt.setEnabled(false);
		
		
		this.getContentPane().add(this.pane);
		this.pane.add(designation);
		this.pane.add(client);
		this.pane.add(box);
		this.pane.add(annee);
		this.pane.add(numero);
		this.pane.add(numeroPlan);
		this.pane.add(commentaire);
		this.pane.add(nbMoules);
		this.pane.add(nbBoites);
		this.pane.add(image);
		this.pane.add(designationTxt);
		this.pane.add(clientBox);
		this.pane.add(boxBox);
		this.pane.add(anneeTxt);
		this.pane.add(numeroTxt);
		this.pane.add(numeroPlanTxt);
		this.pane.add(commentaireTxt);
		this.pane.add(nbMoulesTxt);
		this.pane.add(nbBoitesTxt);
		this.pane.add(imageTxt);
		this.pane.add(okBut);
		this.pane.add(cancBut);
		this.pane.add(parcourirBut);

		this.getContentPane().setLayout(null);
		this.pane.setLayout(null);

		this.pane.setBounds(5,5,540,305);
		this.designation.setBounds(30,20,120,20);
		this.client.setBounds(330,20,120,20);
		this.box.setBounds(330,100,120,20);
		this.annee.setBounds(30,100,120,20);
		this.numero.setBounds(30,60,120,20);
		this.numeroPlan.setBounds(330,60,120,20);
		this.commentaire.setBounds(30,140,120,20);
		this.nbMoules.setBounds(30,180,125,20);
		this.nbBoites.setBounds(290,180,120,20);
		this.image.setBounds(30,220,120,20);
		this.designationTxt.setBounds(150,20,120,20);
		this.numeroTxt.setBounds(150,60,120,20);
		this.numeroPlanTxt.setBounds(410,60,120,20);
		this.boxBox.setBounds(410,100,120,20);
		this.anneeTxt.setBounds(150,100,120,20);
		this.clientBox.setBounds(410,20,120,20);
		this.commentaireTxt.setBounds(150,140,380,20);
		this.nbMoulesTxt.setBounds(160,180,110,20);
		this.nbBoitesTxt.setBounds(410,180,120,20);
		this.imageTxt.setBounds(150,220,230,20);
		this.okBut.setBounds(262,260,115,20);
		this.cancBut.setBounds(412,260,115,20);
		this.parcourirBut.setBounds(412,220,115,20);


		this.okBut.addActionListener(this);
		this.cancBut.addActionListener(this);
		this.parcourirBut.addActionListener(this);
		this.miAjouterC.addActionListener(this);
		this.miRechercherM.addActionListener(this);
		this.miAjouterM.addActionListener(this);
		this.deconnexion.addActionListener(this);
		
		this.okBut.addKeyListener(this);
		this.designationTxt.addKeyListener(this);
		this.anneeTxt.addKeyListener(this);
		this.numeroPlanTxt.addKeyListener(this);
		this.numeroTxt.addKeyListener(this);
		this.nbMoulesTxt.addKeyListener(this);
		this.nbBoitesTxt.addKeyListener(this);
		


		this.setResizable(false);
		this.setVisible(true);
	}

	public void connec(){
		String error = new String();
		error ="";
		String designationAdd	= designationTxt.getText();
		String clientAdd		= ""+clientBox.getSelectedItem();
		String numModeleAdd		= numeroTxt.getText();
		String numPlanAdd		= numeroPlanTxt.getText();
		String boxAdd			= ""+boxBox.getSelectedItem();
		String commentaireAdd	= commentaireTxt.getText();
		String nbMoulesAdd		= nbMoulesTxt.getText();
		String nbBoitesAdd		= nbBoitesTxt.getText();
		String anneeAdd			= anneeTxt.getText();
		int nbMoulesAddTest=1;
		int nbBoitesAddTest=1;
		int anneeAddTest=1;

		if(designationAdd.equals(""))
			error = error + "Pas de désignation\n";
		if(numModeleAdd .equals(""))
			error = error + "Pas de numéro de modèle\n";
		if(nbMoulesAdd .equals("")){
			error = error + "Pas de nombre de moules\n";
			nbMoulesAddTest=0;
		}
		if(nbBoitesAdd.equals("")){
			nbBoitesAddTest=0;
			nbBoitesAdd="0"; // A CHANGER
		}
		if(anneeAdd.equals("")){
			error = error + "Pas d'année\n";
			anneeAddTest=0;
		}

		if(nbMoulesAddTest==1)
		{
			try
			{
				@SuppressWarnings("unused")
				int testInt = Integer.parseInt (nbMoulesAdd);
			}
			catch (NumberFormatException nfe){
				error = error + "Le nombre de moules est incorrect\n";
			}
		}
		if(nbBoitesAddTest==1)
		{
			try
			{
				@SuppressWarnings("unused")
				int testInt = Integer.parseInt (nbBoitesAdd);
			}
			catch (NumberFormatException nfe){
				error = error + "Le nombre de boites est incorrect\n";
			}
		}
		if(anneeAddTest==1){
			try
			{
				int testInt = Integer.parseInt (anneeAdd);
				Calendar cal = new GregorianCalendar();
				int year = cal.get(Calendar.YEAR);
				if (testInt>year)
					error = error + "L'année est incorrecte\n";
			}
			catch (NumberFormatException nfe){
				error = error + "L'année est incorrecte\n";
			}
		}



        int idClientAdd=0;
        int idBoxAdd=0;
        
        if(clientAdd.equals(""))
            error = error + "Pas de client\n";
        else{
            Client clientAddTemp = new Client(clientAdd);
            idClientAdd = clientAddTemp.getID();
        }
        
        if(boxAdd.equals(""))
            error = error + "Pas de box\n";
        else{
            Box boxAddTemp = new Box(boxAdd,1);
            idBoxAdd = boxAddTemp.getID();
        }

		if(error!=""){
			JOptionPane.showMessageDialog(this,error, "Attention", JOptionPane.OK_OPTION,new ImageIcon(getClass().getResource("/icon/warn.png")));
		}
		else
		{


			if(this.imageFile.exists()){
				CopyFile.copyfile(this.imageFile.toString(), ""+pathImage +this.imageFile.getName() );
				this.imageFile = new File(""+pathImage + 
						this.imageFile.getName() );
				Image newImage = new Image(this.imageFile);
				@SuppressWarnings("unused")
				Modele newModele = new Modele(idBoxAdd,idClientAdd,newImage.getID(),designationAdd,numModeleAdd,numPlanAdd,
						commentaireAdd, Integer.parseInt(nbMoulesAdd),Integer.parseInt(nbBoitesAdd),
						Integer.parseInt(anneeAdd));
			}
			else
			{
				@SuppressWarnings("unused")
				Modele newModele = new Modele(idBoxAdd,idClientAdd,0,designationAdd,numModeleAdd,numPlanAdd,
						commentaireAdd, Integer.parseInt(nbMoulesAdd),Integer.parseInt(nbBoitesAdd),
						Integer.parseInt(anneeAdd));
			}
			if(!main.testUpdate)
				JOptionPane.showMessageDialog(this,"Le modèle n'a pas pu être ajouté!", "Attention", JOptionPane.OK_OPTION,new ImageIcon(getClass().getResource("/icon/warn.png")));
			else{
				JOptionPane.showMessageDialog(this,"Le modèle a bien été ajouté", "Model Manager", JOptionPane.OK_OPTION,new ImageIcon(getClass().getResource("/icon/ok.png")));
				this.anneeTxt.setText("");
				this.boxBox.setSelectedIndex(0);
				this.clientBox.setSelectedIndex(0);
				this.commentaireTxt.setText("");
				this.designationTxt.setText("");
				this.imageTxt.setText("");
				this.nbBoitesTxt.setText("");
				this.nbMoulesTxt.setText("");
				this.numeroPlanTxt.setText("");
				this.numeroTxt.setText("");
			}
		}
	}
	public void keyPressed(KeyEvent evt) {

		if ( evt.getKeyCode() == KeyEvent.VK_ENTER)
		{
			this.connec();
		}
	}
	public void keyTyped(KeyEvent evt) { }

	public void keyReleased(KeyEvent evt) {}

	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource() == this.okBut){
			this.connec();
		}
		if(e.getSource()==cancBut)
		{
			
			int q = JOptionPane.showConfirmDialog(this,"Etes-vous sûr de vouloir annuler l'ajout ?", "Annulation", JOptionPane.YES_NO_OPTION);
			if(q==0)
			{
				this.dispose();
				@SuppressWarnings("unused")
				RechercheModele a = new RechercheModele();
			}
		}
		if(e.getSource() == this.miRechercherM){
			//this.setVisible(false);
			this.dispose();
			@SuppressWarnings("unused")
			RechercheModele m = new RechercheModele();
		}
		if(e.getSource() == this.miAjouterM){
			JOptionPane.showMessageDialog(this, "Vous êtes déjà sur le formulaire d'ajout de modèle !", "Attention !",1, new ImageIcon(getClass().getResource("/icon/warn.png")));
		}
		if(e.getSource() == this.miAjouterC){
			this.dispose();
			//this.setVisible(false);
			@SuppressWarnings("unused")
			AjouterClient maFenetre = new AjouterClient();
		}
		if(e.getSource()==parcourirBut)
		{
			JFileChooser chooser = new JFileChooser();
			FileNameExtensionFilter filter = new FileNameExtensionFilter(
					"JPG & GIF Images", "jpg", "gif");
			chooser.setFileFilter(filter);
			int returnVal = chooser.showOpenDialog(this);
			if(returnVal == JFileChooser.APPROVE_OPTION) {
				try {
					System.out.println("You chose to open this file: " +
							chooser.getSelectedFile().toString());
					this.imageTxt.setText(chooser.getSelectedFile().toString());
					this.imageFile=chooser.getSelectedFile();
				} catch (SecurityException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}


		}
		else if(e.getSource() == this.deconnexion){
			this.dispose();
			@SuppressWarnings("unused")
			Connexion c = new Connexion();	
		}
	}


}